package com.yuyou.tas.lesson.controller;

import com.yuyou.tas.lesson.service.IBaseSchoolService;
import com.yuyou.tas.lesson.service.comm.OrganLimitService;
import com.yuyou.tas.service.api.admin.entity.AuthUser;
import com.yuyou.tas.service.api.admin.service.AuthUserAPI;
import com.yuyou.tas.service.api.lesson.dto.DtoBaseSchool;
import com.yuyou.tas.service.api.lesson.entity.BaseSchool;
import com.yuyou.tas.util.bean.*;
import com.yuyou.tas.util.enums.OrganLimitEnums;
import com.yuyou.tas.util.enums.admin.AuthUserEnums;
import com.yuyou.tas.util.exception.BusinessException;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;
import org.hibernate.validator.constraints.NotBlank;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.StringUtils;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import javax.validation.constraints.NotNull;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
@Api(value="BaseSchoolController",description="校区操作接口")
@Validated
@RestController
@RequestMapping(value="/api/BaseSchool")
public class BaseSchoolController extends BaseController {

    @Autowired
    private IBaseSchoolService service;

    @Autowired
    private OrganLimitService organLimitService;

    @Autowired
    private AuthUserAPI authUserAPI;

    @ApiOperation(value="添加校区")
    @RequestMapping(value="/addSchool",method = RequestMethod.POST)
    public ReturnResult addSchool(@Validated @ApiParam(value = "校区名称")@NotBlank(message = "学校名称不能为空")@RequestParam(value = "schoolName") String schoolName,
                                      HttpServletRequest request){
        LoginRedisObj user = this.getUserObj(request);
        ResBoolSimpleInfo info = service.addSchool(schoolName , user,user.getOrganizationId());
        return ReturnResult.returnRes(info.isSuccess() , info.getMessage() , null);
    }

    @ApiOperation(value="删除校区")
    @RequestMapping(value="/delSchool",method = RequestMethod.POST)
    public ReturnResult delSchool(@Validated @ApiParam(value = "校区ID")@NotNull(message = "校区ID不能为空")@RequestParam(value = "id") Long id,
                                  HttpServletRequest request) throws Exception {
        LoginRedisObj user = this.getUserObj(request);
        if(!user.getIsSystem()) {
            organLimitService.checkOrganByOrganId(user.getOrganizationId(), id, OrganLimitEnums.type.base_school);
        }
        ResBoolSimpleInfo info = service.delSchool(id);
        return ReturnResult.returnRes(info.isSuccess() , info.getMessage() , null);
    }


    @ApiOperation(value="通过ID获取校区详情")
    @RequestMapping(value="/getBaseSchool",method = {RequestMethod.GET, RequestMethod.POST})
        public ReturnResult<BaseSchool> getBaseSchool(@Validated @NotNull(message = "ID不能为空")@ApiParam(value = "ID" , required = true) @RequestParam(value = "id") Long id,
                                                      HttpServletRequest request) throws Exception {
        LoginRedisObj user = this.getUserObj(request);
        if(!user.getIsSystem()) {
            organLimitService.checkOrganByOrganId(user.getOrganizationId(), id, OrganLimitEnums.type.base_school);
        }
        ResBoolSimpleInfo info =  service.getSchoolByID(id);
        return ReturnResult.returnRes(info.isSuccess() , info.getMessage() , info.getData());
    }

    @ApiOperation(value="修改校区")
    @RequestMapping(value="/updateSchool",method = RequestMethod.POST)
    public ReturnResult updateSchool(@Validated @ApiParam(value = "校区名称")@NotBlank(message = "学校名称不能为空")@RequestParam(value = "schoolName") String schoolName,
                                        @ApiParam(value = "校区ID")@NotNull(message = "校区ID不能为空")@RequestParam(value = "id") Long id,
                                        HttpServletRequest request) throws Exception {
        LoginRedisObj user = this.getUserObj(request);
        if(!user.getIsSystem()) {
            organLimitService.checkOrganByOrganId(user.getOrganizationId(), id, OrganLimitEnums.type.base_school);
        }
        ResBoolSimpleInfo info = service.updateSchool(schoolName,id);
        return ReturnResult.returnRes(info.isSuccess() , info.getMessage() , null);
    }

    @ApiOperation(value = "查询校区")
    @RequestMapping(value = "/findBaseSchoolPage" ,method = {RequestMethod.GET,RequestMethod.POST})
    public ReturnResult<DtoBaseSchool> findBaseSchoolPage(HttpServletRequest request,
                                                          @Validated @ModelAttribute PageParams pageParams,
                                                          @ApiParam(value = "校区名称")@RequestParam(value = "schoolName" , required = false) String schoolName,
                                                          @ApiParam(value = "是否通过授课班级获取：1、是，0或不传、否，2、根据用户权限获取")@RequestParam(value = "tag",required = false) Integer tag){
        Map<String, Object> conditions = new HashMap<>();
        Pagination<DtoBaseSchool> queryPgn = new Pagination<>();
        queryPgn.setPageParams(pageParams);
        if(!StringUtils.isEmpty(schoolName)){
            conditions.put("schoolName", schoolName.trim());
        }
        LoginRedisObj user = this.getUserObj(request);
        AuthUser authUser = authUserAPI.selectById(user.getUserId());
        if(authUser == null){
            throw new BusinessException("找不到用户信息，请重新登陆");
        }
        if(tag != null && tag == 2 && AuthUserEnums.schoolType.part.getValue() == authUser.getSchoolType()){//根据用户权限获取校区
            conditions.put("userId", user.getUserId());
            queryPgn.setConditions(conditions);

            int total = service.selectByLimitsCount(queryPgn);
            queryPgn.setTotal(total);
            queryPgn.toBePage();
            if(total > 0){
                List<DtoBaseSchool> list = service.selectByLimits(queryPgn);
                queryPgn.setList(list);
            }
        }else if(user.getIsManager() || tag == null || tag != 1){//非教师
            conditions.put("organ_id", user.getOrganizationId());//默认查询个人所在机构的校区
            queryPgn.setConditions(conditions);

            int total = service.findSchoolCount(queryPgn);
            queryPgn.setTotal(total);
            queryPgn.toBePage();
            if(total > 0){
                List<DtoBaseSchool> list = service.findSchoolPageList(queryPgn);
                queryPgn.setList(list);
            }
        }else{//教师角色
            conditions.put("userId", user.getUserId());//查询教师所教班级涉及的校区
            queryPgn.setConditions(conditions);

            int total = service.findTeacherSchoolCount(queryPgn);
            queryPgn.setTotal(total);
            queryPgn.toBePage();
            if(total > 0){
                List<DtoBaseSchool> list = service.findTeacherSchoolPageList(queryPgn);
                queryPgn.setList(list);
            }
        }
        return ReturnResult.success(queryPgn);
    }
		
}
